package com.wellgoon.test.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: Rocky
 * @Date: 2023/5/9
 */
@Configuration
@MapperScan(basePackages="com.wellgoon.mapper.mysql.primary"
        ,sqlSessionTemplateRef = "primaryMySqlSessionTemplate")
public class PrimaryMySQLConfig {
    @Bean(name = "primaryMySqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql.primary")
    @Primary
    public DataSource primaryMySqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "primaryMySqlSessionFactory")
    public SqlSessionFactory primaryMySqlSessionFactory(@Qualifier("primaryMySqlDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "primaryMySqlTransactionManager")
    @Primary
    public DataSourceTransactionManager primaryMySqlTransactionManager(@Qualifier("primaryMySqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "primaryMySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate primaryMySqlSessionTemplate(@Qualifier("primaryMySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
